package com.honeycomb.db.dao.impl;

import java.util.List;
import java.util.Map;
import java.util.Stack;

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import com.honeycomb.common.PositionInfo;
import com.honeycomb.common.base.dao.impl.BaseDaoImpl;
import com.honeycomb.db.dao.UserinfoDao;
import com.honeycomb.user.dto.UserLoginInfo;
import com.honeycomb.user.dto.UserinfoDto;
import com.honeycomb.user.dto.UserinfoDto.Sex;
import com.honeycomb.utils.MD5Utils;
import com.honeycomb.utils.MyDateDTTM;

/**
 * 用户dao实现
 * 
 * @author Wangyu
 */
@Repository
public class UserinfoDaoImpl extends BaseDaoImpl implements UserinfoDao {
	
	private JdbcTemplate jdbcTemplate;
	
	public void setDataSource(DataSource dataSource) {
		this.jdbcTemplate = new JdbcTemplate(dataSource);
	}
	
	@Override
	public UserinfoDto getUserByIdAndPwd(UserLoginInfo loginInf) {
		String sql = "select user_id from user_login where login_id=? and password=? limit 1";
		String psw = loginInf.getPsw();
		String repsw = MD5Utils.generateForPassword(psw);
		
		Object[] val = { loginInf.getLoginId(), repsw };
		List<Long> result = jdbcTemplate.queryForList(sql, val, Long.class);
		
		if (result.size() > 0) {
			Long userId = result.get(0);
			sql = "select * from user_info where user_id=? limit 1";
			Map<String, Object> elem = jdbcTemplate.queryForMap(sql, new Object[]{userId});
			
			UserinfoDto user  = new UserinfoDto((Long) elem.get("user_id"));	
			user.setUserBirthday(new MyDateDTTM((Integer)elem.get("user_birthday") ) );
			user.setUserSex(Sex.getSex((Integer)elem.get("user_sex") ) );
			user.setUserNickname((String)elem.get("user_nickname"));
			user.setUserHeadImagUrl((String) elem.get("user_logo_url"));
			user.setUserRegistIp((String) elem.get("user_regist_ip"));
			user.setUserRegistDttm(new MyDateDTTM((Integer)elem.get("user_regist_dttm") ) );
			user.setStatement((String) elem.get("user_statement"));
			
			return user;
		}
		else{
			return null;
		}
	}
	
	@Override
	public UserinfoDto getUser(Long user_id){
		
		String sql = "select * from user_info where user_id=? limit 1";
		Map<String, Object> elem = jdbcTemplate.queryForMap(sql, new Object[]{user_id});
		
		UserinfoDto user  = new UserinfoDto((Long) elem.get("user_id"));	
		user.setUserBirthday(new MyDateDTTM((Integer)elem.get("user_birthday") ) );
		user.setUserSex(Sex.getSex((Integer)elem.get("user_sex") ) );
		user.setUserNickname((String)elem.get("user_nickname"));
		user.setUserHeadImagUrl((String) elem.get("user_logo_url"));
		user.setUserRegistIp((String) elem.get("user_regist_ip"));
		user.setUserRegistDttm(new MyDateDTTM((Integer)elem.get("user_regist_dttm") ) );
		user.setStatement((String) elem.get("user_statement"));
		
		return user;
	}
	
	@Override 
	public boolean doCheckUserIdAlreadyExist(String loginId){
		String sql = "select login_id from user_login where login_id = ? limit 1";
		Object[] val = {loginId};
		List<Map<String,Object>> result = jdbcTemplate.queryForList(sql,val);
		if(result.size() == 1){
			return true;
		}
		else{
			return false;
		}
	}
	
	@Override
	public UserinfoDto doAdduserinfo(UserLoginInfo loginInfo, UserinfoDto userInfo) {
		
		String sql1 = "insert into user_login(login_id, password) values(?,?)";
		Object[] val1 = {loginInfo.getLoginId(), MD5Utils.generateForPassword(loginInfo.getPsw()) };
		jdbcTemplate.update(sql1, val1);
		
		//get the id of insert.
		Long userId = jdbcTemplate.queryForLong("select LAST_INSERT_ID()");
		if (userId == 0) {
			userId = jdbcTemplate.queryForLong("SELECT user_id FROM user_login WHERE login_id = ?",
														new Object[]{loginInfo.getLoginId()}
													);
		}
		
		
		String sql2 = "insert into user_info values(?,?,?,?,?,?,?,?,?)";
		Object[] val2 = {userId,
						userInfo.getUserNickname(),
						userInfo.getUserSex().toIntValue(),
						userInfo.getUserBirthday().value(),
						loginInfo.getLoginId(),
						userInfo.getUserRegistDttm().value(),
						userInfo.getUserRegistIp(),
						userInfo.getUserHeadImagUrl(),
						userInfo.getStatement()
						};
		
		jdbcTemplate.update(sql2, val2);
		
		UserinfoDto newUser = new UserinfoDto(userId);
		newUser.setUserBirthday(userInfo.getUserBirthday());
		newUser.setUserHeadImagUrl(userInfo.getUserHeadImagUrl());
		newUser.setUserNickname(userInfo.getUserNickname());
		newUser.setUserRegistDttm(userInfo.getUserRegistDttm());
		newUser.setUserRegistIp(userInfo.getUserRegistIp());
		newUser.setUserSex(userInfo.getUserSex());
		newUser.setStatement(userInfo.getStatement());
		
		return newUser;
	}

	
	@Override
	public boolean doUpdate01(UserinfoDto user){
		String sql = "update user_info set user_nickname = ?, user_logo_url = ?, user_birthday = ?, user_statement = ? where user_id = ?";
		
		Object[] val = {
						user.getUserNickname(),
						user.getUserHeadImagUrl(),
						user.getUserBirthday().value(),
						user.getStatement(),
						user.getUserId()
						};
		jdbcTemplate.update(sql,val);
		return true;
	}
	
	@Override
	public boolean doUpdate02(Long userId, UserLoginInfo loginInf) {
		String sql = "update user_login set password = ? where user_id = ?";
		String newPsw = MD5Utils.generateForPassword(loginInf.getPsw());
		Object[] val = {
						newPsw,
						userId
						};
		jdbcTemplate.update(sql,val);
		
		return true;
	}
	
	@Override
	public void doAddPosition(Long userId, PositionInfo position) {
		
			String sql2 = "insert into user_position(user_id, position_type, user_position_lng, user_position_lat, user_position_address, user_position_providerId) values(?,?,?,?,?,?)";
				
			Object[] val2 = {userId,
								position.getType().toIntValue(),
								position.getLongitude(),
								position.getLatitude(),
								position.getAddress(),
								position.getMapProviderId(),
							};
			jdbcTemplate.update(sql2,val2);
	}
	
	@Override
	public Stack<PositionInfo> getFavourPositions(Long userId) {
		String sql = "SELECT position_type, user_position_lng, user_position_lat, user_position_address, user_position_providerId FROM user_position WHERE user_id=? ORDER BY position_type DESC";
		Object[] val = {userId};
		
		List<Map<String,Object>> result = jdbcTemplate.queryForList(sql, val);
		
		Stack<PositionInfo> posiList = new Stack<PositionInfo>();
		PositionInfo posi = null;
		for (Map<String,Object> elem : result){
			posi = new PositionInfo();
			posi.setType(PositionInfo.PositionType.getPositionType( (Integer) elem.get("position_type") ) );
			posi.setLongitude((Double) elem.get("user_position_lng") );
			posi.setLatitude((Double) elem.get("user_position_lat") );
			posi.setAddress((String) elem.get("user_position_address") );
			posi.setMapProviderId((Integer)elem.get("user_position_providerId") );
			
			posiList.add(posi);
		}
		
		return posiList;
	}
	
}
